package com.wus.common.web.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.wus.common.core.account.AccountThreadLocal;
import com.wus.common.core.constant.AccountConstants;
import com.wus.common.core.domain.user.AccountInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Description: 用户上下文设置拦截器
 * @Author: wus
 * @Date: 2024/12/17 11:21
 */
public class UserContextInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(UserContextInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("......进入用户上下文设置拦截器");
        // 微服务之间调用时(gateway例外，它是解析生成上下文的源头)，从上游获取的用户下上文信息
        String accountInfoContextHeader = request.getHeader(AccountConstants.ACCOUNT_INFO_CONTEXT_HEADER);
        if (StrUtil.isNotBlank(accountInfoContextHeader)) {
            logger.info("拦截、解析accountInfoContextHeader={}、设置线程上下文...", accountInfoContextHeader);
            // 获取用户信息 (留给网关解析jwt, 验证redis， 下游服务之间转换 accountInfo json 即可)
            // 将用户信息放入上下文中
            AccountInfo accountInfo = JSONUtil.toBean(accountInfoContextHeader, AccountInfo.class);
            AccountThreadLocal.set(accountInfo);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后，清理线程变量
        AccountThreadLocal.remove();
        logger.info("----清理完AccountThreadLocal");
    }
}
